// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:ffi';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:cbec_app/entity/home/content/scroll_image_slider_entity.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

import '../../pages/goods/binding/goods_detail_binding.dart';
import '../../pages/goods/view/goods_detail_page.dart';
import '../../routes/routes.dart';
import '../common/common_style.dart';

class DecorationCarouselProduct extends StatelessWidget {
  final ScrollImageSliderEntity model;
  const DecorationCarouselProduct({
    super.key,
    required this.model,
  });

  double getTop() {
    return model.pageMarginTop!.toDouble();
  }

  double getBottom() {
    return model.pageMarginBottom!.toDouble();
  }

  double getLeft() {
    return model.pageMarginLeft!.toDouble();
  }

  double getRight() {
    return model.pageMarginRight!.toDouble();
  }

  Color getBgColor() {
    return Tools.fromHex(model.bgColor!);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Tools.fromHex('#f4f4f4'),
      // color: getBgColor(),
      padding: EdgeInsets.only(
        left: getLeft(),
        // top: model.pageMarginTop?.toDouble() ?? 0,
        // bottom: model.pageMarginBottom?.toDouble() ?? 0,
        top: 10,
        bottom: 10,
        right: getRight(),
      ),
      child: Container(
          color: Colors.transparent,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  child: LeftCarouselWidget(
                model: model,
              )),
              Expanded(
                child: RightItemsWidget(model: model),
              ),
            ],
          )),
    );
  }
}

class LeftCarouselWidget extends StatefulWidget {
  final ScrollImageSliderEntity model;
  const LeftCarouselWidget({super.key, required this.model});

  @override
  _LeftCarouselWidgetState createState() => _LeftCarouselWidgetState();
}

class _LeftCarouselWidgetState extends State<LeftCarouselWidget> {
  int _currentIndex = 0; // 当前显示的图片索引

  IndicatorStyle getStyleIndicator() {
    switch (widget.model.indicator) {
      case '1':
        return IndicatorStyle.dots;
      case '2':
        return IndicatorStyle.lines;
      case '3':
        return IndicatorStyle.num;
      case '4':
        return IndicatorStyle.roundedNum;
      default:
        return IndicatorStyle.dots; // Default value, adjust if needed
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 325,
      child: Stack(
        children: [
          if (widget.model.subEntry!.isNotEmpty) ...[
            CarouselSlider.builder(
              itemCount: widget.model.subEntry?.length,
              itemBuilder: (context, index, realIndex) {
                return GestureDetector(
                  onTap: () {
                    var item = widget.model.subEntry![index].toJson();
                    item['link_id'] = int.parse(item['link_id']);
                    Tools.jumpPage(item);
                  },
                  child: SizedBox(
                    height: 325,
                    width: ScreenUtil().screenWidth / 2,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(widget.model.cornerType == '1' ? 0 : 10.0),
                      child: Image.network(
                        widget.model.subEntry![index].imageUrl ?? '',
                        fit: BoxFit.fill,
                        // height: 325,
                      ),
                    ),
                  ),
                );
              },
              options: CarouselOptions(
                aspectRatio: ((ScreenUtil().screenWidth - 20) / 2) / 325.0,
                viewportFraction: 1,
                autoPlay: true, // 自动播放
                autoPlayInterval: Duration(milliseconds: (widget.model.swipeTime ?? 1000)), // 自动播放间隔
                enlargeCenterPage: true, // 中间的图片放大
                pauseAutoPlayOnTouch: true,
                onPageChanged: (index, reason) {
                  setState(() {
                    _currentIndex = index; // 更新当前索引
                  });
                },
              ),
            ),
            // 指示器
            Positioned(
              bottom: 10,
              left: 0,
              right: 0,
              child: Container(
                color: Colors.transparent,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 创建一个 IndicatorWidget，只需要一个
                    IndicatorWidget(
                      currentIndex: _currentIndex,
                      itemCount: widget.model.subEntry!.length,
                      // style: getStyleIndicator(),
                      style: getStyleIndicator(),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}

class RightItemsWidget extends StatelessWidget {
  final ScrollImageSliderEntity model;

  const RightItemsWidget({super.key, required this.model});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min, // 让 Column 自适应高度
      children: [
        // 使用 Wrap 替代 ListView.builder
        Wrap(
          spacing: 5.0, // 水平间距
          runSpacing: 5, // 垂直间距
          children: List.generate(
            model.goods!.length > 2 ? 2 : model.goods?.length ?? 0,
            (index) {
              return CustomListItem(
                styleModel: model,
                good: model.goods![index],
                onTap: () {
                  ScrollImageSliderGoods item = model.goods![index];
                  if (item.commodityId != null) {
                    final id = item.commodityId!;
                    Get.to(
                      () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
                      routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
                      arguments: {"id": id}, // 传递其它参数
                      binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
                    );
                  }
                },
              );
            },
          ),
        ),
      ],
    );
  }
}

class CustomListItem extends StatelessWidget {
  final ScrollImageSliderEntity styleModel;
  final ScrollImageSliderGoods good;
  final VoidCallback onTap;
  const CustomListItem({super.key, required this.styleModel, required this.good, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: SizedBox(
        height: 160,
        child: ProductItem(
          imageUrl: good.mainImage ?? '',
          productName: good.commodityName ?? '',
          price: good.price.toString(),
          origenPrice: good.priceMarket.toString(),
          styleModel: styleModel,
          good: good,
        ),
      ),
    );
  }
}

class ProductItem extends StatelessWidget {
  final ScrollImageSliderEntity styleModel;
  final String imageUrl;
  final String productName;
  final String price;
  final String origenPrice;
  final ScrollImageSliderGoods good;

  const ProductItem({
    super.key,
    required this.imageUrl,
    required this.productName,
    required this.price,
    required this.styleModel,
    required this.origenPrice,
    required this.good,
  });

  String getTitleColor() {
    return styleModel.titleColor!;
  }

  String getPriceColor() {
    return styleModel.priceColor!;
  }

  String getOldPriceColor() {
    return styleModel.oldpriceColor!;
  }

  BoxDecoration getBoxDecoration() {
    String sizeType = styleModel.sizeType!;
    // border_radius_type 1直角 2圆角
    String borderRadiusType = styleModel.borderRadiusType!;
    BorderRadius borderRadius = borderRadiusType == '1' ? BorderRadius.zero : const BorderRadius.all(Radius.circular(5));

    switch (sizeType) {
      case '0':
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
      case '1':
        return DecorationProvider.getDecoration(ContainerStyleType.cardShadow, borderRadius);
      case '2':
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
      case '3':
        return DecorationProvider.getDecoration(ContainerStyleType.noBorderTransparent, borderRadius);
      default:
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
    }
  }

  ///商品图片圆角
  double getRadius() {
    return styleModel.borderRadiusType == '1' ? 0.0 : 3.0;
  }

  EdgeInsets getImageFillStyle() {
    String imageFillStyle = styleModel.imageFillStyle!;
    return imageFillStyle == '1' ? EdgeInsets.zero : const EdgeInsets.symmetric(horizontal: 5, vertical: 20);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 5, right: 8),
      decoration: getBoxDecoration(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        // mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(styleModel.imageStyle == '1' ? 0 : 10),
              child: Image.network(
                imageUrl,
                width: styleModel.imageFillStyle! == '1' ? double.infinity : 50,
                height: 50.0, // 可以调整这个高度
                fit: BoxFit.cover,
              ),
            ),
          ),
          const SizedBox(height: 8.0),
          Visibility(
            visible: styleModel.showTitle ?? true,
            child: Text(
              productName,
              style: TextStyle(color: Tools.fromHex(styleModel.titleColor ?? '#000000'), fontSize: 12.0, fontWeight: FontWeight.normal),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(height: 8.0),
          SizedBox(
            width: double.infinity,
            child: Wrap(
              runSpacing: 5.w,
              children: [
                for (var text in good.discountLabel!)
                  BorderedText(
                    text: text,
                    padding: const EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
                    borderColor: ThemeConfig.themeColor,
                    textStyle: const TextStyle(fontSize: 11, color: ThemeConfig.themeColor),
                  ),
              ],
            ),
          ),
          const SizedBox(height: 8.0),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Visibility(
                visible: true,
                child: RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: '¥',
                        style: TextStyle(
                          fontSize: 12.0,
                          color: Tools.fromHex(styleModel.priceColor ?? '#000000'), // 设置 ¥ 的样式
                        ),
                      ),
                      TextSpan(
                        text: price,
                        style: TextStyle(
                          fontSize: 16.0,
                          color: Tools.fromHex(styleModel.priceColor ?? '#000000'), // 设置价格的样式
                          fontWeight: FontWeight.normal, // 示例：可为价格加粗
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Visibility(
                visible: styleModel.showOriginPrice ?? true,
                child: Text.rich(
                  TextSpan(
                    text: '¥$origenPrice', // 原价文本
                    style: TextStyle(fontSize: 10.0, color: Tools.fromHex(styleModel.oldpriceColor ?? '#000000'), decoration: TextDecoration.lineThrough), // 设置划线
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

// 指示器样式枚举
enum IndicatorStyle {
  dots, // 小圆点
  lines, // 短线
  num, // 索引/总页数
  roundedNum, // 带圆角背景的索引/总页数
}

class IndicatorWidget extends StatelessWidget {
  final int currentIndex; // 当前索引
  final int itemCount; // 总项数
  final IndicatorStyle style; // 指示器样式

  const IndicatorWidget({
    super.key,
    required this.currentIndex,
    required this.itemCount,
    this.style = IndicatorStyle.dots,
  });

  @override
  Widget build(BuildContext context) {
    switch (style) {
      case IndicatorStyle.dots:
        return _buildDotsIndicator();
      case IndicatorStyle.lines:
        return _buildLinesIndicator();
      case IndicatorStyle.num:
        return _buildIndexIndicator();
      case IndicatorStyle.roundedNum:
        return _buildRoundedIndexIndicator(); // 新增的样式
      default:
        return const SizedBox.shrink();
    }
  }

  // 带圆角背景的索引/总页数样式
  Widget _buildRoundedIndexIndicator() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0x80000000), // 背景颜色
        borderRadius: BorderRadius.circular(20.0), // 圆角
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 4.0), // 内边距
      child: Text(
        '${currentIndex + 1} / $itemCount',
        style: const TextStyle(
          fontSize: 16.0,
          fontWeight: FontWeight.normal,
          color: Colors.white,
        ),
      ),
    );
  }

  // 小圆点样式
  Widget _buildDotsIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(itemCount, (index) {
        return GestureDetector(
          onTap: () {
            // TODO: 添加点击逻辑
          },
          child: Container(
            width: 8.0,
            height: 8.0,
            margin: const EdgeInsets.symmetric(horizontal: 4.0),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: (currentIndex == index) ? Colors.grey : Colors.grey.withOpacity(0.4),
            ),
          ),
        );
      }),
    );
  }

  // 短线样式
  Widget _buildLinesIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(itemCount, (index) {
        return Container(
          width: 20.0,
          height: 4.0,
          margin: const EdgeInsets.symmetric(horizontal: 4.0),
          color: (currentIndex == index) ? Colors.grey : Colors.grey.withOpacity(0.4),
        );
      }),
    );
  }

  // 索引/总页数样式
  Widget _buildIndexIndicator() {
    return Text(
      '${currentIndex + 1} / $itemCount',
      style: const TextStyle(
        fontSize: 16.0,
        fontWeight: FontWeight.bold,
      ),
    );
  }
}
